package com.bookstore.servlet;

import com.bookstore.entity.Product;
import com.bookstore.service.ProductService;
import com.bookstore.service.impl.ProductServiceImpl;
import org.apache.commons.fileupload.FileItem;
import org.apache.commons.fileupload.FileUploadException;
import org.apache.commons.fileupload.disk.DiskFileItemFactory;
import org.apache.commons.fileupload.servlet.ServletFileUpload;

import javax.servlet.ServletException;
import javax.servlet.annotation.WebServlet;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.*;
import java.util.List;

@WebServlet("/admin/product.do")
public class ProductServlet extends HttpServlet {
    ProductService productService = new ProductServiceImpl();

    @Override
    protected void doGet(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        String action = req.getParameter("action");
        System.out.println(action);
        if ("query".equals(action)) {
            query(req, resp);
        }else if ("add".equals(action)) {
            addProduct(req, resp);
        }else if ("delete".equals(action)) {
            deleteProduct(req, resp);
        }else if ("update".equals(action)) {
            updateProduct(req, resp);
        }else {
            uploadImg(req, resp);
        }



    }

    private void uploadImg(HttpServletRequest req, HttpServletResponse resp) throws IOException, ServletException {
        System.out.println(1234);
        String uploadPath = "D:\\Java Coding\\imgUpload";
        String tempPath = "D:\\Java Coding\\imgUpload\\temp";
        if (ServletFileUpload.isMultipartContent(req)) {
            DiskFileItemFactory factory = new DiskFileItemFactory();
            factory.setSizeThreshold(1 * 1024 * 1024);//设置缓存
            factory.setRepository(new File(tempPath));

            ServletFileUpload upload = new ServletFileUpload(factory);
            upload.setFileSizeMax(2 * 1024 * 1024);//设置单个文件上传大小
            //upload.setSizeMax(10*1024*1024);//设置一次上传多个文件大小
            String filePath = null;
            try {
                List<FileItem> fileItems = upload.parseRequest(req);
                if (!new File(uploadPath).isDirectory()) {
                    new File(uploadPath).mkdirs();
                }
                for (int i = 0; i < fileItems.size(); i++) {
                    FileItem item = fileItems.get(i);
                    if (!item.isFormField()) {
                        String fileName = item.getName();
                        filePath=uploadPath+"\\"+fileName;
                        File file = new File(filePath);
                        try {
                            item.write(file);
                            System.out.println(fileName);
                        } catch (Exception e) {
                            e.printStackTrace();
                        }
                    }
                }
            } catch (FileUploadException e) {
                e.printStackTrace();
            }

        }
        resp.sendRedirect("./product.do?action=query");


//                String imgurl = req.getParameter("imgurl");
//        String filePath = req.getParameter("filePath");
//        System.out.println(imgurl);
//        System.out.println(filePath);
//        File srcfile=new File(filePath);
//
//        File targetfile=new File("D:\\Java Coding\\imgUpload\\"+imgurl);
//        FileInputStream fileInputStream = new FileInputStream(srcfile);
//        FileOutputStream fileOutputStream = new FileOutputStream(targetfile);
//        byte[] buffer = new byte[1024];
//        int length = 0;
//        while ((length = fileInputStream.read(buffer)) != -1) {
//            fileOutputStream.write(buffer,0,length);
//            fileOutputStream.flush();
//        }
//        fileInputStream.close();
//        fileOutputStream.close();

    }

    private void updateProduct(HttpServletRequest req, HttpServletResponse resp) throws IOException {

        String id = req.getParameter("id");
        String name = req.getParameter("name");
        String price = req.getParameter("price");
        String category = req.getParameter("category");
        String pnum = req.getParameter("pnum");
        String imgurl = req.getParameter("imgurl");
        String description = req.getParameter("description");
        Product product = new Product(Integer.parseInt(id), name, Double.parseDouble(price), category, Integer.parseInt(pnum), imgurl, description);
        int result = productService.update(product);
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        if (result > 0) {
            writer.write("1");
        } else {
            writer.write("0");
        }
    }

    private void deleteProduct(HttpServletRequest req, HttpServletResponse resp) {
        String productID = req.getParameter("productID");
        productService.delete(Integer.parseInt(productID));

    }

    private void addProduct(HttpServletRequest req, HttpServletResponse resp) throws IOException {
        String name = req.getParameter("name");
        String price = req.getParameter("price");
        String category = req.getParameter("category");
        String pnum = req.getParameter("pnum");
        String imgurl = req.getParameter("imgurl");
        String description = req.getParameter("description");
        Product product = new Product(null, name, Double.parseDouble(price), category, Integer.parseInt(pnum), imgurl, description);
        int result = productService.insert(product);
        resp.setContentType("text/html;charset=UTF-8");
        PrintWriter writer = resp.getWriter();
        if (result > 0) {
            writer.write("1");
        } else {
            writer.write("0");
        }

    }

    private void query(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        List<Product> products = productService.queryAll();
        req.setAttribute("products", products);
        req.getRequestDispatcher("/admin/product_list.jsp").forward(req, resp);

    }

    @Override
    protected void doPost(HttpServletRequest req, HttpServletResponse resp) throws ServletException, IOException {
        doGet(req, resp);
    }
}
